package com.estore.network;

import com.estore.model.Product;
import com.estore.service.ProductSorters;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

public class EStoreClient {
    private static final String SERVER_HOST = "localhost";
    private static final int SERVER_PORT = 8888;
    private final Map<String, Integer> shoppingCart = new HashMap<>(); // 标记为final
    private final Scanner scanner = new Scanner(System.in); // 标记为final

    public static void main(String[] args) {
        new EStoreClient().start();
    }

    public void start() {
        System.out.println("=== 欢迎使用C/S架构商城系统 ===");
        boolean running = true;
        while (running) {
            showMenu();
            try {
                int choice = Integer.parseInt(scanner.nextLine().trim());
                switch (choice) {
                    case 1:
                        browseProducts(null);
                        break;
                    case 2:
                        sortAndBrowse();
                        break;
                    case 3:
                        addToCart();
                        break;
                    case 4:
                        viewCart();
                        break;
                    case 0:
                        running = false;
                        System.out.println("感谢使用，再见！");
                        break;
                    default:
                        System.out.println("无效选项，请重新输入");
                }
            } catch (NumberFormatException e) {
                System.out.println("请输入数字选项！");
            }
        }
        scanner.close();
    }

    private void showMenu() {
        System.out.println("\n===== 操作菜单 =====");
        System.out.println("1. 浏览所有商品");
        System.out.println("2. 按条件排序商品");
        System.out.println("3. 添加商品到购物车");
        System.out.println("4. 查看购物车");
        System.out.println("0. 退出系统");
        System.out.print("请选择：");
    }

    private void browseProducts(Comparator<Product> comparator) {

        List<Product> products;
        try (Socket socket = new Socket(SERVER_HOST, SERVER_PORT);
             ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
             ObjectInputStream ois = new ObjectInputStream(socket.getInputStream())) { // try-with-resources

            oos.writeObject("GET_ALL_PRODUCTS");
            oos.flush();

            Object response = ois.readObject();
            // 消除“未检查的转换”
            if (response instanceof List<?>) {
                List<?> rawList = (List<?>) response;
                if (!rawList.isEmpty() && rawList.get(0) instanceof Product) {
                    products = (List<Product>) rawList;
                } else {
                    products = new ArrayList<>();
                }
            } else {
                System.out.println("服务器响应错误：" + response);
                return;
            }

            if (comparator != null) {
                products.sort(comparator);
            } else {
                Collections.sort(products);
            }

            System.out.println("\n===== 商品列表 =====");
            for (Product p : products) {
                System.out.println(p);
            }

        } catch (IOException | ClassNotFoundException e) {
            System.err.println("获取商品列表失败：" + e.getMessage());
            products = new ArrayList<>(); // 异常分支初始化
        }
    }

    private void sortAndBrowse() {
        System.out.println("\n===== 排序方式 =====");
        System.out.println("1. 价格从低到高");
        System.out.println("2. 价格从高到低");
        System.out.println("3. 库存从多到少");
        System.out.print("请选择：");

        try {
            int choice = Integer.parseInt(scanner.nextLine().trim());
            Comparator<Product> comparator = null;
            switch (choice) {
                case 1:
                    comparator = ProductSorters.BY_PRICE_ASC;
                    break;
                case 2:
                    comparator = ProductSorters.BY_PRICE_DESC;
                    break;
                case 3:
                    comparator = ProductSorters.BY_STOCK_DESC;
                    break;
                default:
                    System.out.println("无效排序方式，使用默认排序");
            }
            browseProducts(comparator);
        } catch (NumberFormatException e) {
            System.out.println("请输入数字！");
        }
    }

    private void addToCart() {
        System.out.print("\n请输入商品ID：");
        String id = scanner.nextLine().trim();
        Product product = getProductById(id);

        if (product == null) {
            System.out.println("商品不存在！");
            return;
        }
        if (product.getStock() <= 0) {
            System.out.println("商品已售罄！");
            return;
        }

        try {
            System.out.print("请输入购买数量：");
            int quantity = Integer.parseInt(scanner.nextLine().trim());
            if (quantity <= 0) {
                System.out.println("数量必须大于0！");
                return;
            }
            if (quantity > product.getStock()) {
                System.out.println("库存不足！当前库存：" + product.getStock());
                return;
            }

            shoppingCart.put(id, shoppingCart.getOrDefault(id, 0) + quantity);
            System.out.println("已添加 " + product.getName() + " x " + quantity + " 到购物车");
        } catch (NumberFormatException e) {
            System.out.println("请输入有效数量！");
        }
    }

    private Product getProductById(String id) {
        List<Product> allProducts;
        try (Socket socket = new Socket(SERVER_HOST, SERVER_PORT); // try-with-resources
             ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
             ObjectInputStream ois = new ObjectInputStream(socket.getInputStream())) {

            oos.writeObject("GET_ALL_PRODUCTS");
            oos.flush();
            Object response = ois.readObject();
            // 消除“未检查的转换”
            if (response instanceof List<?>) {
                List<?> rawList = (List<?>) response;
                if (!rawList.isEmpty() && rawList.get(0) instanceof Product) {
                    allProducts = (List<Product>) rawList;
                } else {
                    allProducts = new ArrayList<>();
                }
            } else {
                allProducts = new ArrayList<>();
            }

            for (Product p : allProducts) {
                if (p.getId().equals(id)) {
                    return p;
                }
            }
        } catch (Exception e) {
            System.err.println("查询商品失败：" + e.getMessage());
            allProducts = new ArrayList<>();
        }
        return null;
    }

    private void viewCart() {
        System.out.println("\n===== 我的购物车 =====");
        if (shoppingCart.isEmpty()) {
            System.out.println("购物车为空！");
            return;
        }

        double total = 0.0;
        for (Map.Entry<String, Integer> entry : shoppingCart.entrySet()) {
            String productId = entry.getKey();
            int quantity = entry.getValue();
            Product product = getProductById(productId);

            if (product != null) {
                double subtotal = product.getPrice() * quantity;
                total += subtotal;
                System.out.printf("%s（ID：%s） x %d，单价：%.2f，小计：%.2f%n",
                        product.getName(), productId, quantity, product.getPrice(), subtotal);
            }
        }
        System.out.printf("===== 总计：%.2f 元 =====%n", total);
    }
}